package com.yonyou.pmclouds.workquality.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.conf.PMCloudServerProperties;
import com.yonyou.pmclouds.basecom.consts.EnableStatusConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.HttpTookit;
import com.yonyou.pmclouds.basecom.util.operation.EncryptUtil;
import com.yonyou.pmclouds.industryandtype.entity.IndustryAndTypeRefVO;
import com.yonyou.pmclouds.industryandtype.rmiitf.IndustryAndTypeQuery;
import com.yonyou.pmclouds.industryandtype.rmiitf.TypeDocQuery;
import com.yonyou.pmclouds.picture.entity.PictureVO;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/workquality")
@RestController
public class WorkqualityController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkqualityQueryService queryService;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkqualityService service;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IndustryAndTypeQuery industryAndTypeQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TypeDocQuery typeDocQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private PictureRemoteService pictureRemoteService;

    @Autowired
    private PMCloudServerProperties pmcloudServerProperties;

    @RequestMapping(value = "/search")
    public Map<String, Object> search(@RequestParam(required = false) String keyword, @RequestParam(required = false) Integer start, @RequestParam(required = false) Integer size,
                                      @RequestParam(value = "status", required = false) Integer status) throws BusinessException {
        byte enableStatus = EnableStatusConst.ALL;
        if (status != null && status != EnableStatusConst.ALL)
            enableStatus = status.byteValue();

        return queryService.queryByCondition(keyword, start, size, enableStatus);
    }

    @RequestMapping(value = "/delete")
    public void delete(@RequestBody @Validated WorkqualityVO workqualityVO, BindingResult errors) throws BusinessException {
        service.delete(workqualityVO);
    }

    @GetMapping(value = "/searchWeb")
    public List<WorkqualityVO> search(@RequestParam(name = "tenantId") String tenantId, @RequestParam(name = "billType") String billType) throws BusinessException {
        // 单据类型的过滤
        int[] checkTypes = new WorkqualityMobController().convertBillType2CheckType(billType);
        // 除了综合验收类型检查标准，其他都能查看到
        List<WorkqualityVO> workqualityVOs = queryService.queryByChecktypes(tenantId, checkTypes);

        return workqualityVOs;
    }
    @RequestMapping(value = "/add")
    public WorkqualityVO add(@RequestBody @Validated WorkqualityVO workqualityVO, BindingResult errors) throws BusinessException {
        if (errors.hasErrors()) {
            throw new IllegalRequestArgException();
        }
        workqualityVO.setPkTenant(RuntimeEnvironment.getTenantId());
        workqualityVO.setEnableStatus(EnableStatusConst.ENABLE);
        workqualityVO = service.insert(workqualityVO);
        return workqualityVO;
    }

    @RequestMapping(value = "/load")
    public WorkqualityVO load(@RequestBody WorkqualityVO workqualityVO) throws BusinessException {
        workqualityVO = queryService.queryByIDFull(workqualityVO.getPkWorkquality());
        return workqualityVO;
    }

    @RequestMapping(value = "/finish")
    public WorkqualityVO finish(@RequestBody @Validated WorkqualityVO workqualityVO, BindingResult errors) throws BusinessException {
        workqualityVO = service.update(workqualityVO);
        return workqualityVO;
    }


    /**
     * 查看所有的行业和质量标准对应的类型，返回行业和类型的组合型数据实体
     *
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/queryIndustryAndType")
    public IndustryAndTypeRefVO[] queryIndustryAndType() throws BusinessException {

        String result = HttpTookit.doGet(pmcloudServerProperties.getYwaddress() + "/workquality/queryIndustryAndType", null);
        JSONObject json = JSONObject.parseObject(result);
        String jsonString = json.getString("result");


        List<IndustryAndTypeRefVO> list = JSONArray.parseObject(jsonString, new TypeReference<ArrayList<IndustryAndTypeRefVO>>() {
        });
        return list.toArray(new IndustryAndTypeRefVO[]{});
        //IndustryAndTypeRefVO[] result = industryAndTypeQuery.queryIndustryAndType(TypeConst.TYPE_WORKQUALITY);
        //return result == null ? new IndustryAndTypeRefVO[0] : result;
    }

    /**
     * 根据选中的类型，预览类型对应的质量标准
     *
     * @param pkType
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/queryPreviewWorkqualitys")
    public com.yonyou.pmclouds.operation.WorkqualityVO[] queryPreviewWorkqualitys(@RequestParam("pkType") String pkType) throws BusinessException {
        if (StringUtils.isEmpty(pkType)) {
            return new com.yonyou.pmclouds.operation.WorkqualityVO[0];
        }

        Map<String, String> params = new IdentityHashMap<>();
        params.put(new String("pkTypes[]"), pkType);
        String data = "pmCloud_" + System.currentTimeMillis();
        try {
            EncryptUtil encryptUtil = new EncryptUtil(pmcloudServerProperties.getDeSkey(), "utf-8");
            String result = encryptUtil.encode(data);
            params.put("key", result);
        } catch (Exception e) {
            throw new BusinessException("参数加密失败");
        }

        String result = HttpTookit.doGet(pmcloudServerProperties.getYwaddress() + "/data/opr/workqualitys/queryPreviewWorkqualitys", params);
        if (StringUtils.isEmpty(result)) {
            return new com.yonyou.pmclouds.operation.WorkqualityVO[0];
        }
        JSONObject json = JSONObject.parseObject(result);
        String jsonString = json.getString("result");

        List<com.yonyou.pmclouds.operation.WorkqualityVO> list = JSONArray.parseObject(jsonString, new TypeReference<ArrayList<com.yonyou.pmclouds.operation.WorkqualityVO>>() {
        });
        return list.toArray(new com.yonyou.pmclouds.operation.WorkqualityVO[]{});

//        WorkqualityVO[] result = service.getPreviewWorkqualitys(pkType);
//        return result == null ? new WorkqualityVO[0] : result;
    }

    /**
     * 用户导入质量标准预置模板
     *
     * @param pkTypes
     * @return
     * @throws BusinessException
     */
    @PostMapping("/insertWorkqualitysFromPreset")
    public String[] insertWorkqualitysFromPreset(@RequestBody String[] pkTypes) throws BusinessException {
        if (ArrayUtils.isEmpty(pkTypes)) {
            return new String[0];
        }

        Map<String, String> params = new IdentityHashMap<>();
        for (String pkType : pkTypes) {
            params.put(new String("pkTypes[]"), pkType);
        }

        String data = "pmCloud_" + System.currentTimeMillis();
        try {
            EncryptUtil encryptUtil = new EncryptUtil(pmcloudServerProperties.getDeSkey(), "utf-8");
            String result = encryptUtil.encode(data);
            params.put("key", result);
        } catch (Exception e) {
            throw new BusinessException("参数加密失败");
        }

        String result = HttpTookit.doGet(pmcloudServerProperties.getYwaddress() + "/data/opr/workqualitys/queryPreviewWorkqualitys", params);
        JSONObject json = JSONObject.parseObject(result);
        String jsonString = json.getString("result");


        List<WorkqualityVO> list = JSONArray.parseObject(jsonString, new TypeReference<ArrayList<WorkqualityVO>>() {
        });

        String[] ids = service.insertPresetWorkqualitys(list);
        return ids == null ? new String[0] : ids;
    }

    @PostMapping("/enable")
    public WorkqualityVO enable(@RequestBody WorkqualityVO workqualityVO) throws BusinessException {
        WorkqualityVO result = service.enable(workqualityVO);

        return result;
    }

    @PostMapping("/disable")
    public WorkqualityVO disable(@RequestBody WorkqualityVO workqualityVO) throws BusinessException {
        WorkqualityVO result = service.disable(workqualityVO);

        return result;
    }

    @PostMapping("/referCheck")
    public void referCheck(@RequestBody WorkqualityVO workqualityVO) throws BusinessException {
        queryService.referCheck(workqualityVO);
    }

    @GetMapping("/getPicsOfItem")
    public PictureVO[] queryExamplePicsOfItem(@RequestParam("pkDetail") String pkDetail) throws BusinessException {
        return pictureRemoteService.queryExamplePicsByEntity(pkDetail);
    }

    @RequestMapping("/copyWorkQuality")
    public String updateCopyWorkQuality(@RequestParam("tenantId") String tenantId, @RequestParam("srcCheckType") int srcCheckType,
                                        @RequestParam("toCheckType") int toCheckType) throws BusinessException {
        return service.updateCopyWorkQuality(tenantId, srcCheckType, toCheckType);
    }

}
